package com.gxd.business.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.gxd.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MybatisPlus自动填充
 * @author gxd
 * @since 2025/6/18
 */
@Slf4j
@Component
public class AutoFillHandler implements MetaObjectHandler {

    /**
     * 插入时自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = String.valueOf(SecurityUtils.getUserId());
        Date date = new Date();
        this.strictInsertFill(metaObject, "createBy", String.class, userId);
        this.strictInsertFill(metaObject, "createTime", Date.class, date);
        this.strictUpdateFill(metaObject, "updateBy", String.class, userId);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, date);
    }

    /**
     * 更新时自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(SecurityUtils.getUserId()));
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }
}
